import config from '../core/config'

var objectURL = config.overview
var getListeners = []
var isYouTubeID = function(s) {
  return /^[A-Za-z0-9_-]{11}$/.test(s)
}

// var Objects =

export default {
  $objects: null,
  objectIndex: null,
  get: function(callback) {
    if (this.$objects) {
      callback(this.$objects, this.objectIndex);
    } else {

      getListeners.push(callback);

      if (getListeners.length === 1) {
        var self = this;

        // 发起请求
        fetch(objectURL).then(res => res.json()).then(objectArr => {
          self.$objects = [];
          self.objectsByCategory = {};
          self.objectIndex = {};

          objectArr.forEach(function(obj) {
            const { categoryName } = obj

            // 将类型名字转为小写
            obj.categoryName = (categoryName + '').toLowerCase();

            // 唯一 ID
            if (!self.objectsByCategory[obj.categoryName]) {
              self.objectsByCategory[obj.categoryName] = [];
            }
            self.objectsByCategory[obj.categoryName].push(obj);

            // 绑定到每个节点上
            if (obj.categoryName === 'null') {
              obj.categoryObjects = [];
            } else {
              obj.categoryObjects = self.objectsByCategory[obj.categoryName];
            }

            obj.bullet = obj.bullet.replace(/[^a-z0-9]/gi, '-');

            if (!self.objectIndex[obj.bullet]) {

              self.objectIndex[obj.bullet] = obj;

              self.$objects.push(obj);

              obj.mapParams = {
                center: {lat: obj.lat, lng: obj.lng},
                zoom: obj.zoomLevel
              };

            } else {
              //console.log('duplicate object!', obj.bullet);
            }
          });

          for (var i in self.objectsByCategory) {
            self.objectsByCategory[i].sort(function(a,b) { return a.dateCreated - b.dateCreated; });
          }

          getListeners.forEach(function(f) { f(self.$objects, self.objectIndex); });

          getListeners = [];
        });
      }
    }
  }
};
